package com.newcapce.chat;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class Server {
    public static void main(String[] args) throws IOException {
        //服务器监听端口
        ServerSocket serverSocket = new ServerSocket(1111);
        System.out.println("服务端启动,监听端口1111.....");
        List<Socket> socketList = new ArrayList<>();
        //循环等待客户端连接
        while(true){
            Socket socket = serverSocket.accept();
            socketList.add(socket);
            System.out.println(socket.getRemoteSocketAddress()+"连接成功");
            sendToAll(socket.getRemoteSocketAddress()+"连接成功",socketList);
            System.out.println("当前在线人数:"+socketList.size());
            //存储客户端信息

            new Thread(){
                @Override
                public void run() {
                    try {
                        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                        while(true){
                            String revStr = dataInputStream.readUTF();
                            System.out.println("服务端转发:"+revStr);
                            //转发给所有人
                            sendToAll(revStr,socketList);
                        }
                    } catch (IOException e) {
                        //e.printStackTrace();
                       System.out.println(socket.getRemoteSocketAddress()+"断开连接");
                        socketList.remove(socket);
                        sendToAll(socket.getRemoteSocketAddress()+"断开连接",socketList);
                        System.out.println("当前在线人数:"+socketList.size());
                    }
                }
            }.start();
        }
    }

    private static void sendToAll(String revStr, List<Socket> socketList) {
        for(Socket socket:socketList){
            try {
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeUTF(revStr);
                dataOutputStream.flush();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
